"""验证 GeoJSON 文件的几何结构，确保坐标为 [经度, 纬度] 对"""

import json
from pathlib import Path

def is_number_sequence(seq):
    return all(isinstance(x, (int, float)) for x in seq)

def validate_geojson(path):
    path = Path(path)
    data = json.loads(path.read_text(encoding='utf-8'))
    bad = []
    for i, feat in enumerate(data.get('features', [])):
        geom = feat.get('geometry')
        if not geom:
            bad.append((i, 'no geometry'))
            continue
        coords = geom.get('coordinates')
        if coords is None:
            bad.append((i, 'no coordinates'))
            continue
        # only check first ring existence
        try:
            first = coords[0]
        except Exception:
            bad.append((i, 'coordinates not nested as expected'))
            continue
        # detect single-number lists or lists of single numbers as shown in your file
        def scan(x):
            if isinstance(x, (int, float)):
                return True
            if isinstance(x, list) and len(x)>0 and is_number_sequence(x):
                # numbers but maybe intended pair? length 1 or >2
                if len(x) != 2:
                    return True
            return False
        # perform a shallow check of the first few entries
        sample = first[:10] if isinstance(first, list) else []
        if any(scan(s) for s in sample):
            bad.append((i, 'coordinate entries appear malformed (not [lng,lat])'))
    return data, bad

if __name__ == "__main__":
    src = Path(__file__).parents[1] / "data" / "processed" / "shenzhen_voronoi_communities.geojson"
    print("Validating:", src)
    data, bad = validate_geojson(src)
    if not bad:
        print("✅ GeoJSON looks structurally OK (basic checks).")
    else:
        print("❌ Found malformed features (index, reason):")
        for idx, reason in bad:
            props = data['features'][idx].get('properties', {})
            print(f"  - feature #{idx} name={props.get('name')} id={props.get('id')} => {reason}")
        print("\n建议：使用原始中心点重新生成 Voronoi（确保 vertices 为 [lng,lat] 对），或手工修复 GeoJSON。")